import Request from 'luch-request';
import { Local } from '@/utils/storage';
import errorCode from '@/utils/errorCode';
let isRedirectingToLogin = false; // 避免多次跳转登录页
const http = new Request();
/**
 * @description 修改全局默认配置
 * @param {Function}
 */
http.setConfig((config) => {
	config.baseURL = import.meta.env.VITE_API_URL;
	config.custom = {
		loading: true,
	};
	return config;
});

/**
 * 在请求之前拦截
 */
http.interceptors.request.use(
	(config: any) => {
		if (config.custom.loading) {
			uni.showLoading({
				title: '加载中',
			});
		}

		const token = Local.getToken();
		// token
		if (token && !config.custom.skipToken) {
			config.header['satoken'] = token;
		}
		// 租户ID
		config.header['tenant-id'] = import.meta.env.VITE_TENANT_ID;
		// #ifdef MP
		config.header['app-id'] = uni.getAccountInfoSync().miniProgram.appId;
		// #endif
		//#ifdef MP-WEIXIN
		config.header['client-type'] = 'WX_MA'; //客户端微信小程序
		//#endif
		//#ifdef APP-PLUS
		config.header['client-type'] = 'APP'; //客户端APP
		//#endif
		//#ifdef H5
		config.header['client-type'] = 'H5'; //客户端H5
		//#endif
		if (JSON.parse(import.meta.env.VITE_OPEN_BOOT)) {
			config.url = config.url = `/boot/${config.url?.split('/').splice(2).join('/')}`;
		}
		return config;
	},
	(config) => {
		return Promise.reject(config);
	}
);
/**
 * 在请求之后拦截
 */
http.interceptors.response.use(
	(response) => {
		// 隐藏加载状态提示
		uni.hideLoading();

		if (response.data.code === 401) {
			if (!isRedirectingToLogin) {
				isRedirectingToLogin = true;
				Local.clear();
				setTimeout(() => {
					uni.$hxRouter.push({
						url: '/pages/login/index',
					});
					isRedirectingToLogin = false;
				}, 500);
			}
			return Promise.reject(response);
		}
		if (response.data.code !== 0) {
			uni.showToast({
				icon: 'none',
				title: response.data.msg,
				duration: 2000,
			});
			return Promise.reject(response);
		}
		return response.data;
	},
	(response) => {
		// 隐藏加载状态提示
		uni.hideLoading();
		const status = response.statusCode;
		const msg = errorCode[status] || '未知错误';
		uni.$emit('z-paging-error-emit', msg);
		uni.showToast({
			icon: 'none',
			title: msg,
			duration: 2000,
		});
		return Promise.reject(response);
	}
);

export default http;
